<?php
namespace App\Core;

use App\Helper\Utils;
use App\Repositories\FileRepository;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;

class Uploader
{
    /**
     * @Inject
     * @var ConfigInterface
     */
    private $config;

    public function __construct(ConfigInterface $config)
    {
        $this->config = $config;
    }

    public function uploadBySlice(RequestInterface $request)
    {
        $tmp = $this->config->get('common.tmp_upload_dir');
        $upload_dir = $this->config->get('common.upload_dir');
        $path = date('Ym').'/'.date('d').'/';
        $dir = $upload_dir.$path;
        $this->createdir($dir);
        $file = $request->file('file');//上传分片文件
        $orgFileName = $request->input('orgFileName');//原始文件名称
        $uploadFileName = $request->input('filename');//保存后文件名称
        $filename = explode("." , $uploadFileName);
        $ext = $filename[1];
        $filename = $filename[0];
        if(!file_exists($tmp.$filename)){
            $this->createdir($tmp.$filename);
        }
        $frag_name = $request->input('slicename');
        $frag_path = $tmp.$filename ."/".$frag_name;
        $file->moveTo($frag_path);
        $current_slice_index = $request->input('index');
        $total_slice_num = $request->input('total');
        //合并file文件夹中的slice为最终文件
        if( $current_slice_index == $total_slice_num-1 ){
            $blob='';
            for($i=0; $i<$total_slice_num; $i++){
                $blob .= file_get_contents($tmp.$filename.'/'.'slice-'.$i);
                @unlink($tmp.$filename.'/'.'slice-'.$i);
            }
            file_put_contents( $dir. $filename . "." .$ext , $blob );
            @rmdir($tmp.$filename);
            //执行插入数据库操作
            $file_data =[
                'user_id'=>1,
                'is_admin'=>1,
                'album_id'=>0,
                'file_name'=>$orgFileName,
                'extension'=>$ext,
                'path'=>'/uploads/'.$path.$filename.'.'.$ext,
                'size'=>$request->input('size'),
                'mime'=>$request->input('mime'),
                'is_image'=>in_array($request->input('mime'),['image/png','image/gif','image/jpeg'])?1:0
            ];
            $model = FileRepository::getInstance()->store($file_data);
            return [
                'success' => true,
                'status' => 'done',
                'path' => '/uploads/'.$path.$filename.'.'.$ext,
                'url' => $this->config->get('common.image_prefix').'/uploads/'.$path.$filename.'.'.$ext,
            ];
        }
        return [
            'success' => true,
            'url' => '',
            'status' => 'uploading',
            'percent' => '',
            'path' => ''
        ];
    }

    public function uploadByFile(RequestInterface $request)
    {
        $file = $request->file('file');
        $extension = $file->getExtension();
        $dir = '/uploads/'.date('Ym').'/'.date('d').'/';
        $folder = BASE_PATH.'/public'.$dir;
        $this->createdir($folder);
        $newname = Utils::createFileName();
        $file->moveTo($folder.$newname.'.'.$extension);
        if ($file->isMoved()) {
            return [
                'success' => true,
                'path' => $dir.$newname.'.'.$extension,
                'url' => $this->config->get('common.image_prefix').$dir.$newname.'.'.$extension,
            ];
        }
        return ['success'=>false];
    }

    public function uploadByBase64($base64_img)
    {
        $base64_string = $base64_img;
        $base64_0=explode(',', $base64_string);
        $base64_1=explode('/', $base64_0['0']);
        $base64_2=explode(';', $base64_1['1']);
        $s = base64_decode(str_replace(''.$base64_0['0'].',','',$base64_string));
        $newname = Utils::createFileName().'.'.$base64_2['0'];
        $dir = '/uploads/'.date('Ym').'/'.date('d').'/';
        $folder = BASE_PATH.'/public'.$dir;
        $this->createdir($folder);
        $image= file_put_contents($folder.$newname, $s);
        return [
            'success' => true,
            'path' => $dir.$newname,
            'url' => $this->config->get('common.image_prefix').$dir.$newname
        ];
    }

    private function createdir($dir)
    {
        if (!is_dir($dir)) {
            return mkdir($dir, 0777, true);
        }
        return true;
    }
}
